package com.springboot.idempotence.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
/**
 * redis 操作
 * @author cgj
 */
@Component
public class RedisService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 写入redis 缓存
     *
     * @author cgj
     */
    public boolean set(String key, Object value) {
        try {
            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 写入redis 缓存 并设置过期时间
     *
     * @author cgj
     */
    public boolean setEx(String key, Object value, Long expireTime) {
        try {
            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断redis 缓存中是否有对应的value
     *
     * @author cgj
     */
    public boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 根据入参(key) 读取redis 缓存的值
     *
     * @author cgj
     */
    public Object get(String key) {
        ValueOperations operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    /**
     * 删除入参(key) 在Redis 缓存中的值
     *
     * @author cgj
     */
    public boolean remove(String key) {
        if (exists(key)) {
            return redisTemplate.delete(key);
        }
        return false;
    }
}
